<?php
class Line_related_destination_model extends CI_Model
{
    private $table = 'line_related_destination';
    private $table_2 = 'line_destination';
    private $table_3 = 'region';
    
    public function saveRelatedLineBase($line_id, $destination_id)
    {
        $data = $this->convertArray($line_id, $destination_id);
        $result = $this->db->insert_batch($this->table, $data);
        if ($result) {
            return true;
        }
        return false;
    }
    
    /**
     * 将一维数组转换成多位数组
     * @param string $string
     * @param array $array
     * @return Ambigous <multitype:, array>
     */
    private function convertArray($string, array $array)
    {
        $data = array();
        foreach ($array as $key=>$value) {
            $data[$key]['line_id'] = $string;
            $data[$key]['destination_id'] = $value;
        }
        return $data;
    }
    
    public function findByLineIdDestination($line_id)
    {
        $this->db->select('line_destination.*');
        $this->db->from($this->table.' as line_related_destination');
        $this->db->join($this->table_2.' as line_destination', 'line_related_destination.destination_id = line_destination.destination_id');
        $this->db->where('line_related_destination.line_id', $line_id);
        return $this->db->get();
    }
    
    public function findByLineIdDestinationList($line_id)
    {
        $this->db->select('line_destination.*');
        $this->db->from($this->table.' as line_related_destination');
        $this->db->join($this->table_2.' as line_destination', 'line_related_destination.destination_id = line_destination.destination_id');
        $this->db->where('line_related_destination.line_id', $line_id);
        $this->db->order_by('line_related_destination.id','desc');
        return $this->db->get();
    }
    
    public function ajaxInsertDestination($line_id, $destination_id)
    {
        $data = array(
           'line_id'             => $line_id,
           'line_destination_id' => $destination_id
        );
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }
    
    public function getLineIdsDestination($line_ids)
    {
        $this->db->select('line_destination.address');
        $this->db->from($this->table.' as line_related_destination');
        $this->db->join($this->table_2.' as line_destination', 'line_related_destination.destination_id = line_destination.destination_id');
        $this->db->where_in('line_related_destination.line_id', $line_ids);
        return $this->db->get();
    }
    
    public function deleteByLineId($line_id)
    {
        $this->db->where('line_id', $line_id);
        return $this->db->delete($this->table);
    }
}